
/* server.js 服务器 */

const WebSocket = require('ws');

// 创建WebSocket服务器
const server = new WebSocket.Server({ port: 3000 });

// 监听连接事件
server.on('connection', (socket) => {
  console.log('WebSocket connected.');


  // 监听消息事件
  socket.on('message', (message) => {
    console.log('message========>', message);
    setInterval(() => {
      let obj = { time: new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds(), value: randomNum(-20, 20) }
      socket.send(JSON.stringify(obj))
    }, 200)
  });

  // 监听关闭事件
  socket.on('close', () => {
    console.log('断开链接');
  });
});

//模拟后台获取数据
function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}

console.log('WebSocket server listening on port 3000...');

